# -*- coding: utf-8 -*-
#!/usr/local/env    python

import os, sys
from wsgiref.simple_server import make_server
from random import randint
import yaml
import functools
import local_method

try:
    import urllib.request as get_exporter_data
except ImportError:
    import urllib as get_exporter_data

url_view_map = dict()
config_map = dict()
all_method = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEADER", "OPTIONS"]

root_dir = os.path.dirname(os.path.abspath(__file__))

def parse_conf(config_file):
    with open(root_dir.replace("\\", "/") + "/" + config_file) as f:
        config = yaml.safe_load(f)
    return config

def gen_url_map(url, method="GET"):
    if method not in all_method:
        print("request method '%s' illegal, use GET instead, please check it")
        method = "GET"
    url = url if not url.endswith("/") or len(url) == 1 else url[:-1]
    def wrapper(fn):
        @functools.wraps(fn)
        def decorator(*args, **kwargs):
            return fn(*args, **kwargs)
        url_view_map[url] = [fn, method]
        return decorator
    return wrapper

def exec_local_method():
    body = ""
    for fn in local_method.get_metrics_with_local_methods:
        body += fn()
    print(body)
    return body

def get_metrics_from_exporter(exporter_url):
    metrics = get_exporter_data.urlopen(exporter_url).read()
    if not isinstance(metrics, str):
        metrics = metrics.decode("utf-8")
    return metrics

def get_matrics_from_scripts(scripts_path):
    body = ""
    for script in os.listdir(scripts_path):
        stdout = os.popen("sh %s" % scripts_path + "/" + script)
        body += stdout.read()
    return body

@gen_url_map("/", "GET")
def get_index(environ, start_response):
    start_response('200 OK', [("Content-Type", "text/html; version=0.0.4; charset=utf-8")])
    content = """
    <html>
        <head>
            <title>Node Exporter</title>
        </head>
        <body>
            <h1>Custom Exporter</h1>
            <p><a href="/metrics">Metrics</a></p>
        </body>
    </html>
    """
    return content

@gen_url_map("/metrics", "GET")
def get_data(environ, start_response):
    body = ""
    for exporter_name, exporter_url in config_map["exporter_list"].items():
        try:
            body += get_metrics_from_exporter(exporter_url)
        except Exception as e:
            print("error: get matrics filed from %s" % exporter_name)
            print(e)
    
    body += exec_local_method()

    for script_path_name, script_path in config_map["script_path_list"].items():
        body += get_matrics_from_scripts(script_path)

    start_response('200 OK', [("Content-Type", "text/plain; version=0.0.4; charset=utf-8")])
    return body

def application(environ, start_response):
    """
    environ 是请求过来的数据
    start_response 设置请求头
    """

    request_url = environ.get("PATH_INFO", None)
    if request_url not in url_view_map.keys():
        start_response('404 not found', [("Content-Type", "text/plain; version=0.0.4; charset=utf-8")])
        return ["sorry, there have no ico".encode("utf-8")]

    body = url_view_map[request_url][0](environ, start_response)
    return [body.encode('utf-8')]

def main():
    try:
        config_file = sys.argv[1]
    except IndexError:
        config_file = "config.yml"
    global config_map
    config_map = parse_conf(config_file)
    print(config_map)
    # u"创建一个服务器，IP地址为空，端口是8000，处理函数是application:"
    httpd = make_server(config_map["address"]["host"], int(config_map["address"]["port"]), application)
    print("Serving HTTP on %s:%s ..." % (config_map["address"]["host"], config_map["address"]["port"]))
    # u"开始监听HTTP请求:"
    httpd.serve_forever()

if __name__ == "__main__":
    main()
